const app = getApp();
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const foot = require('../../templates/foot/index.js');
const {
  $Toast
} = require('../../components/base/base');

Page({

  data: {
    navBg: app.globalData.navBg,
    navColor: app.globalData.navColor,
    windowHeight: app.globalData.windowHeight - app.globalData.navHeight,
    navTop: app.globalData.navHeight,
    back: true,
    navBox: true,
    home: true,
    checkAll: false,
    totalCount: 0,
    totalPrice: 0,
    hasList: true,
    cart: [], //数据
    count: 1, //商品数量默认是1
    total: 0, //总金额
    goodsCount: 0, //数量
    management_good: false,
    disabled: true,
    allSelect: true,
    noSelect: false,
    goTop: true,
    scrollHeight: app.globalData.windowHeight - app.globalData.navHeight - 40,
    counts: 1
  },

  toIndexBtn: function() {
    util.navigateTo('../index/index')
  },

  //计算商品总数
  calculateTotal: function(e) {
    var that = this;
    var cart = this.data.cart;
    var totalCount = 0;
    var totalNumber = 0;
    var totalPrice = 0;
    for (var i = 0; i < cart.length; i++) {
      var good = cart[i];
      if (good.checked) {
        totalCount += good.count;
        totalPrice += good.count * good.price;
      }
      totalNumber += parseInt(good.count);
    }
    totalPrice = totalPrice.toFixed(2);
    that.setData({
      totalCount: totalCount,
      totalPrice: totalPrice,
      navCont: parseInt(totalNumber)
    })

  },

  // 批量加入购物车
  allAddCart: function(e) {
    var that = this;
    var arr = wx.getStorageSync('shopCollect') || [];
    var arr2 = [];
    var atr = [];
    var cart = wx.getStorageSync('shopCart') || [];
    var newArr = [];

    for (var i = 0; i < arr.length; i++) {
      var checks = arr[i].checked // 获取当前缓存商品的状态
      atr.push(checks)
    }
    //根据缓存商品状态判断当前商品是否选中
    if (atr.includes(false) && !atr.includes(true)) {

      $Toast({
        content: "请选择商品!",
        icon: 'prompt_fill',
        duration: 1
      });
    } else {
      wx.showModal({
        title: '',
        confirmText: "确定",
        confirmColor: "#e93b3d",
        cancelText: "取消",
        cancelColor: "#333",
        content: '您确定要加入购物车吗？',
        success: function(res) {
          if (res.confirm) {
            for (var i = 0; i < arr.length; i++) {
              var curItem = arr[i];
              if (curItem.checked) {
                cart.push(curItem)
              }
            }
            // js数组对象相同值相加，不同添加
            cart.forEach(item => {
              var dataItem = item
              if (newArr.length > 0) {
                var filterValue = newArr.filter(v => {
                  return v.id == dataItem.id
                })
                if (filterValue.length > 0) {
                  newArr.forEach(n => {
                    if (n.id == filterValue[0].id) {
                      n.count = parseInt(filterValue[0].count + dataItem.count)
                    }
                  })
                } else {
                  newArr.push(dataItem)
                }
              } else {
                newArr.push(dataItem)
              }

            })
            that.setGoodsCart(that.allSelect(), that.noSelect(), newArr);
            setTimeout(() => {
              $Toast({
                content: "加入购物车成功！",
                icon: 'success',
                duration: 1
              });
            }, 600);
          } else if (res.cancel) {

          }
        }
      })
    }
  },

  // 批量取消
  deleteitem: function(e) {
    var that = this;
    var arr = wx.getStorageSync('shopCollect') || [];
    var arr2 = [];
    var atr = [];
    for (var i = 0; i < arr.length; i++) {
      var checks = arr[i].checked // 获取当前缓存商品的状态
      atr.push(checks)
    }
    //根据缓存商品状态判断当前商品是否选中
    if (atr.includes(false) && !atr.includes(true)) {

      $Toast({
        content: "请选择商品!",
        icon: 'prompt_fill',
        duration: 1
      });
    } else {
      wx.showModal({
        title: '',
        confirmText: "确定",
        confirmColor: "#e93b3d",
        cancelText: "取消",
        cancelColor: "#333",
        content: '您确认要取消关注吗？',
        success: function(res) {
          if (res.confirm) {
            var cart = that.data.cart;
            for (var i = 0; i < cart.length; i++) {
              var curItem = cart[i];
              if (curItem.checked) {
                var cart = that.data.cart;
                cart.splice(i--, 1);
                that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
                if (!cart.length) {
                  that.setData({
                    hasList: false,
                    checkAll: false,
                    totalPrice: 0
                  });
                }
                setTimeout(() => {
                  $Toast({
                    content: "取消成功！",
                    icon: 'success',
                    duration: 1
                  });
                }, 600);
              }
            }

          } else if (res.cancel) {

          }
        }
      })
    }
  },


  // 加入购物车
  addCartPlus: function(e) {
    var that = this;
    var itemdetail = wx.getStorageSync('shopCollect') || [];
    var id = e.currentTarget.dataset.id;

    $Toast({
      content: "加入购物车成功!",
      icon: 'success',
      duration: 1
    });

    for (var i = 0; i < itemdetail.length; i++) {
      if (itemdetail[i].id == id) {
        // 给itemdetail数组的当前项添加count元素，值为1，用于记录添加到购物车的数量
        itemdetail[i].count = parseInt(that.data.counts);
        itemdetail[i].checked = true;
        var arr = wx.getStorageSync('shopCart') || [];
        if (arr.length > 0) {
          for (var j in arr) {
            if (arr[j].id == id) {
              arr[j].count = arr[j].count + parseInt(that.data.counts);
              try {
                wx.setStorageSync('shopCart', arr)
              } catch (e) {
                console.log(e)
              }
              return;
            }
          }
          arr.push(itemdetail[i]);
        } else {
          arr.push(itemdetail[i]);
        }

        try {
          wx.setStorageSync('shopCart', arr)
          return;
        } catch (e) {
          console.log(e)
        }
      }
    }

  },

  //点击商品减1
  minCart: function(e) {
    var that = this;
    var index = e.target.dataset.index;
    var cart = that.data.cart;
    if (index !== "" && index != null) {
      if (cart[parseInt(index)].count > 1) {
        cart[parseInt(index)].count--;
        that.setData({
          counts: cart[parseInt(index)].count
        })
        that.setGoods(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
      } else {
        wx.showModal({
          title: '',
          confirmText: "确定",
          confirmColor: "#e93b3d",
          cancelText: "取消",
          cancelColor: "#333",
          content: '您确认要取消关注吗？',
          success: function(res) {
            if (res.confirm) {
              cart.splice(index, 1);
              that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
              if (!cart.length) {
                that.setData({
                  hasList: false,
                  checkAll: false,
                  totalPrice: 0
                });
              } else { // 如果不为空
                that.calculateTotal(); // 重新计算总价格
              }
              setTimeout(() => {
                $Toast({
                  content: "取消成功！",
                  icon: 'success',
                  duration: 1
                });
              }, 600);
            } else if (res.cancel) {

            }
          }
        })
      }
    }

  },

  //点击商品加1
  addCart: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var cart = this.data.cart;
    if (index !== "" && index != null) {
      cart[parseInt(index)].count++;
      that.setData({
        counts: cart[parseInt(index)].count
      })
      that.setGoods(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
    }
  },

  // 监听输入
  cartNum: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var cart = this.data.cart;
    cart[parseInt(index)].count = e.detail.value.replace(/[^0-9]/g, '')
    that.setData({
      counts: e.detail.value.replace(/[^0-9]/g, '')
    })
  },

  allSelect: function() {
    var cart = this.data.cart;
    var allSelect = false;
    for (var i = 0; i < cart.length; i++) {
      var curItem = cart[i];
      if (curItem.checked) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    return allSelect;
  },

  noSelect: function() {
    var cart = this.data.cart;
    var noSelect = 0;
    for (var i = 0; i < cart.length; i++) {
      var curItem = cart[i];
      if (!curItem.checked) {
        noSelect++;
      }
    }
    if (noSelect == cart.length) {
      return true;
    } else {
      return false;
    }
  },

  setGoodsList: function(total, allSelect, noSelect, cart) {
    this.setData({
      allSelect: allSelect,
      noSelect: noSelect,
      cart: cart
    });
    wx.setStorage({
      key: "shopCollect",
      data: cart
    })
  },

  setGoods: function(total, allSelect, noSelect, cart) {
    this.setData({
      allSelect: allSelect,
      noSelect: noSelect,
      cart: cart
    });

  },

  setGoodsCart: function (allSelect, noSelect, cart) {
    this.setData({
      allSelect: allSelect,
      noSelect: noSelect
    });
    wx.setStorage({
      key: "shopCart",
      data: cart
    })
  },

  // 选择商品
  checkboxChange: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var cart = this.data.cart;
    if (index !== "" && index != null) {
      cart[parseInt(index)].checked = !cart[parseInt(index)].checked;
      that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
    }
    let str = true; //用str与每一项进行状态判断        
    for (var i = 0; i < cart.length; i++) {
      str = str && cart[i].checked; //用str与每一项进行状态判断
    }
    if (str === true) {
      that.setData({
        checkAll: true
      })
    } else {
      that.setData({
        checkAll: false
      })
    }

  },

  //全选
  selectalltap: function(e) {
    var that = this;
    var checkAll = !this.data.checkAll;
    var cart = this.data.cart;
    let arr2 = [];
    if (checkAll) {
      for (var i = 0; i < cart.length; i++) {
        cart[i].checked = true;
        arr2.push(cart[i]);
      }
    } else {
      for (var i = 0; i < cart.length; i++) {
        cart[i].checked = false;
        arr2.push(cart[i]);
      }
    }
    that.setData({
      checkAll: checkAll
    });
    that.setGoodsList(that.calculateTotal(), !checkAll, that.noSelect(), cart);
  },

  checkChange: function(e) {
    var that = this;
    var value = e.detail.value
    if (value.length != 0) {
      that.setData({
        disabled: false
      })
    } else {
      that.setData({
        disabled: true
      })
    }

  },

  checkChangeAll: function(e) {
    var that = this;
    var value = e.detail.value
    if (value.length != 0) {
      that.setData({
        disabled: false
      })
    } else {
      that.setData({
        disabled: true
      })
    }

  },

  // 管理商品
  management: function() {
    let that = this;
    that.setData({
      management_good: true,
    })
  },

  finish_management: function() {
    let that = this;
    that.setData({
      management_good: false,
    })
  },

  gotoDetail: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    util.navigateTo('../productdetail/productdetail?id=' + id)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    var cart = that.data.cart;
    // 获取产品展示页保存的缓存数据（购物车的缓存数组，没有数据，则赋予一个空数组）
    var arr = wx.getStorageSync('shopCollect') || [];
    // 有数据的话，就遍历数据，计算总金额 和 总数量
    if (arr.length > 0) {
      that.data.cart = arr;
      that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), arr);
      for (var i in arr) {
        that.data.total += Number(arr[i].price) * Number(arr[i].count);
        that.data.goodsCount += Number(arr[i].count);
      }
      // 更新数据
      that.setData({
        hasList: true,
        cart: arr,
        total: that.data.total,
        goodsCount: that.data.goodsCount
      });

      //判断全选按钮状态
      var atr = [];
      for (var i = 0; i < arr.length; i++) {
        var checks = arr[i].checked // 获取当前缓存商品的状态
        atr.push(checks)
        if (arr[i].checked == true) {
          that.setData({
            disabled: false
          });
        } else {
          that.setData({
            disabled: true
          });
        }
      }

      if (atr.includes(false)) { //判断是否存在false
        that.setData({
          checkAll: false
        })

      } else {
        that.setData({
          checkAll: true
        })
      }

      var found = false;
      for (var i = 0; i < arr.length; i++) {
        var checks = arr[i].checked // 获取当前缓存商品的状态
        if (arr[i].checked == true) {
          that.setData({
            disabled: false
          });
          found = true;
          break;
        } else {
          that.setData({
            disabled: true
          });
        }
      }

    } else {
      that.setData({
        hasList: false
      });
    }
  },

  scroll: function(e) {
    var that = this;
    var listIndex = (e.detail.scrollTop + this.data.screenHeight) / (this.data.screenWidth * 0.4)
    if (e.detail.scrollTop > app.globalData.navHeight + 40) {
      this.setData({
        goTop: false
      });
      this.setData({
        listIndex: listIndex
      })
    } else {
      this.setData({
        goTop: true
      });
    }

  },

  //返回顶部
  goScrolltop: function(e) {
    var that = this;
    var top = that.data.scrollTop;
    if (top == 1) {
      top = 0;
    } else {
      top = 1;
    }

    that.setData({
      scrollTop: top
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }


})